package com.software.task.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import com.software.task.mapper.CategoryMapper;
import com.software.task.mapper.HomeworkMapper;
import com.software.task.pojo.Homework;
import com.software.task.pojo.PageBean;
import com.software.task.service.HomeworkService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 李嘉
 * @since 2024/12/16 13:50
 * @version 1.0
 */
@Service
public class HomeworkServiceImpl implements HomeworkService {

    private final HomeworkMapper homeworkMapper;

    private final CategoryMapper categoryMapper;

    public HomeworkServiceImpl(HomeworkMapper homeworkMapper, CategoryMapper categoryMapper) {
        this.homeworkMapper = homeworkMapper;
        this.categoryMapper = categoryMapper;
    }

    /**
     * 添加作业
     *
     * @param homework 作业对象
     */
    @Override
    public void add(Homework homework) {
        homeworkMapper.add(homework);
    }

    /**
     * 获取所有已提交的作业
     *
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param teacherId 教师ID
     * @return 分页后的作业列表
     */
    @Override
    public PageBean<Homework> getAllSubmittedSubjects(Integer pageNum, Integer pageSize, Integer teacherId) {
        PageBean<Homework> pageBean = new PageBean<>();
        PageHelper.startPage(pageNum, pageSize);
        List<Homework> homeworkList = homeworkMapper.listByState("已提交",teacherId);
        // 遍历 Homework 列表，设置 subjectName
        for (Homework homework : homeworkList) {
            Integer categoryId = homework.getCategoryId();
            if (categoryId != null) {
                String subjectName = categoryMapper.getCategoryNameById(categoryId);
                homework.setSubjectName(subjectName);
            }
        }
        Page<Homework> page = (Page<Homework>) homeworkList;
        pageBean.setTotal(page.getTotal());
        pageBean.setItems(page.getResult());
        return pageBean;
    }

    /**
     * 打分作业
     *
     * @param id 作业ID
     * @param grade 作业分数
     * @return 更新后的作业分数
     */
    @Override
    public Integer gradeHomework(Integer id, Integer grade) {
        homeworkMapper.gradeHomework(id, grade);
        return homeworkMapper.getGradeById(id);
    }
}